import jwt
from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from rest_framework.filters import SearchFilter
from rest_framework import generics, permissions
from rest_framework.authentication import TokenAuthentication
from home.models import UserProfile, TieziModel, TagModel, LianjieModel
from home.serializers import UserProfileSer, TieziSer, TagSer, LianjieSer

# views.py
from rest_framework.filters import DjangoFilterBackend  # 新增

class UserProfileView(ModelViewSet):
    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSer
    lookup_field = 'id'
    lookup_url_kwarg = 'id'

class TagView(ModelViewSet):
    queryset = TagModel.objects.all()
    serializer_class = TagSer
    lookup_field = 'id'
    lookup_url_kwarg = 'id'


class LianjieView(ModelViewSet):
    queryset = LianjieModel.objects.all()
    serializer_class = LianjieSer
    lookup_field = 'id'
    lookup_url_kwarg = 'id'
    filter_backends = [DjangoFilterBackend]  # 新增过滤后端

    filterset_fields = ['l_tag']  # 允许根据 l_tag 字段过滤



# 展示帖子
class TieziView(ModelViewSet):
    queryset = TieziModel.objects.all()
    serializer_class = TieziSer
    lookup_field = 'id'
    lookup_url_kwarg = 'id'




# 添加帖子
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from home.models import TieziModel, TagModel, LianjieModel
from home.serializers import CreateTieziSerializer
from myapp.models import User
from utils.jwttool import tooljwt
import logging

logger = logging.getLogger(__name__)

class CreateTieziView(APIView):
    def post(self, request):
        # 验证Token
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return Response({'error': '未提供认证令牌'}, status=status.HTTP_401_UNAUTHORIZED)

        token = auth_header.split(' ')[1]
        try:
            payload = tooljwt.checkToken(token)
        except Exception as e:
            return Response({'error': '令牌验证失败', 'detail': str(e)}, status=status.HTTP_401_UNAUTHORIZED)

        # 获取用户ID
        userid = payload.get('userid')
        try:
            userid = int(userid)
        except (ValueError, TypeError):
            return Response({'error': '无效的用户ID'}, status=status.HTTP_400_BAD_REQUEST)

        # 获取用户
        try:
            user = User.objects.get(id=userid)
        except User.DoesNotExist:
            logger.error(f"数据库中未找到 userid 为 {userid} 的用户")
            return Response({'error': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)

        # 创建帖子
        serializer = CreateTieziSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(t_user=user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)



# from rest_framework import generics
# from .models import TieziModel
# from .serializers import TieziSerializer  # 你需要创建这个序列化器
#
# class TieziCreateView(generics.CreateAPIView):
#     queryset = TieziModel.objects.all()
#     serializer_class = TieziSerializer
#
#     def perform_create(self, serializer):
#         serializer.save(t_user=self.request.user)


# views.py
# from django.shortcuts import render
# from rest_framework.viewsets import ModelViewSet
# from rest_framework.views import APIView
# from rest_framework.response import Response
# from rest_framework.pagination import PageNumberPagination
# from rest_framework.filters import SearchFilter
# from rest_framework import generics, permissions
# from rest_framework.authentication import TokenAuthentication
# from home.models import UserProfile, TieziModel, TagModel, LianjieModel
# from home.serializers import UserProfileSer, TieziSer, TagSer, LianjieSer
#
# class StandardResultsSetPagination(PageNumberPagination):
#     page_size = 10
#     page_size_query_param = 'page_size'
#     max_page_size = 100
#
# class TieziView(ModelViewSet):
#     queryset = TieziModel.objects.all()
#     serializer_class = TieziSer
#     lookup_field = 'id'
#     lookup_url_kwarg = 'id'
#     pagination_class = StandardResultsSetPagination
#     filter_backends = [SearchFilter]
#     search_fields = ['t_title', 't_content']
#     authentication_classes = [TokenAuthentication]
#     permission_classes = [permissions.IsAuthenticatedOrReadOnly]


